import React, { useEffect, useState } from "react";
import type { SelectProps } from "./type";
import { Type } from "./components/enum";
import { isDef } from "@ct0/functions";
import DropdownSelect from "./components/index";

export default Select;

function Select(props: SelectProps) {
  const [options, setOptions] = useState(props.options);

  useEffect(() => setOptions(props.options), [props.options]);

  const handleValueChange = (value: Array<string | number>) => {
    if (props.multiple) props.onChange?.(value);
    else props.onChange?.(value[0]);
  };

  const handleSearchValueChange = (
    text: string,
    value: Array<string | number>
  ) => {
    if (!!text)
      setOptions(
        props.options.filter((x) =>
          x.label.toLowerCase().includes(text.toLowerCase())
        )
      );
    else setOptions(props.options);
    if (props.multiple) props.onInputChange?.(text, value);
    else props.onInputChange?.(text, value[0]);
  };

  const type = props.multiple ? Type.MULTI_CHOICE : Type.SINGLE_CHOICE;

  const selectValue =
    typeof props.value === "undefined"
      ? []
      : props.multiple
      ? props.value
      : [props.value];

  const filterSelectValue = selectValue?.filter((v) => isDef(v));

  const allowClearAll = props.multiple && props.allowClearAll;
  const allowSelectAll = props.multiple && props.allowSelectAll;
  const rest = props.multiple
    ? {
        disabledValueOptions: props.disabledValueOptions,
      }
    : {};

  return (
    <DropdownSelect
      value={filterSelectValue}
      search={props.search}
      disabled={props.disabled}
      placeholder={props.placeholder}
      type={type}
      className={props.className}
      style={props.style}
      options={options}
      allowClear={props.allowClear}
      allowClearAll={allowClearAll}
      allowSelectAll={allowSelectAll}
      onChange={handleValueChange}
      onInputChange={handleSearchValueChange}
      invalid={props.invalid}
      dropdownRender={props.dropdownRender}
      notFoundContent={props?.notFoundContent}
      {...rest}
    />
  );
}
